import {getInfo, login, logout} from '@/api/user/user'
import {getToken, removeToken, setToken} from '@/utils/auth'
import router, {resetRouter} from '@/router'
import md5 from 'js-md5'
import {baseUrl} from '@/api/constant'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  points: [],
  profile: false
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_POINTS: (state, points) => {
    state.points = points
  },
  SET_PROFILE: (state, profile) => {
    state.profile = profile
  },
};

const actions = {
  /**
   * 用户登录
   * @param commit
   * @param userInfo
   */
  loginByUserName({commit}, userInfo) {
    const {username, password} = userInfo;
    return new Promise((resolve, reject) => {
      login({lpUserName: username.trim(), lpUserPassword: md5(password)}).then(response => {
        const {data} = response;
        commit('SET_TOKEN', data)
        setToken(data)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  /**
   * 获取个人信息
   * @param commit
   * @param state
   * @returns {Promise<any>}
   */
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo().then((response) => {

        if (!response.data) {
          reject('验证失败，请重新登录...');
        }
        const {lpUserName, lpUserUrl, menuList, menuMap} = response.data;
        const roles = [];

        if (menuList.length > 0) {
          menuList.forEach((value) => {
            roles.push(value.menuEnName)
          });
        }

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('用户角色权限为空,请联系管理员');
        }

        const {data} = {
          "data": {
            "roles": roles,
            "avatar": lpUserUrl,
            "name": lpUserName
          }
        };

        commit('SET_ROLES', data.roles)
        commit('SET_POINTS', menuMap)
        commit('SET_NAME', lpUserName)
        commit('SET_AVATAR', lpUserUrl)

        resolve(data)
      }).catch((error) => {
        reject(error)
      })
    })
  },


  /**
   * 后端-登出
   * @param commit
   * @param state
   * @param dispatch
   * @returns {Promise<any>}
   */
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      logout().then((res) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // 重置已访问的视图和缓存的视图
        dispatch('tagsView/delAllViews', null, {root: true})
        resolve()
      }).catch((error) => {
        reject(error)
      })
    })
  },

  /**
   * 前端-登出
   * @param commit
   * @returns {Promise<any>}
   */
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');
      removeToken();
      resolve();
    })
  },

  /**
   * 动态地修改权限
   * @param commit
   * @param dispatch
   * @param role
   * @returns {Promise<any>}
   */
  changeRoles({commit, dispatch}, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const {roles} = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {root: true})

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {root: true})

      resolve()
    })
  },

  /**
   * 个人资料
   */
  changeProfile({commit}, profile) {
    commit('SET_PROFILE', profile)
  },

  /**
   * 更新头像
   */
  changeAvatar({commit}, avatar) {
    commit('SET_AVATAR', avatar)
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

